<!--
    group: 发票管理
    name: 申请开票
    item: 开票类目子组件
-->
<template>
  <div>
    <div v-for="(item,index) in taxContents">
      <InvoicingDropDownItem
        :item="item" :index="index"
         v-bind="$attrs" v-on="$listeners"
         :optionData="getTreeData"
      />

      <a-row v-if="!moneyDisabled" type="flex" justify="space-between">
        <a-col :span='6' class="rightLine tone">
          <a-button
            type="link" icon="minus"
            style="color: #cc0000;margin-top: 5px;"
            v-if="index != 0"
            @click="deleteRateFun(item.invoiceTypeCode,index)"
          >删除应税项目</a-button>
        </a-col>
        <a-col :span='2' class="align rightLine tone"></a-col>
        <a-col :span='2' class="align rightLine tone"></a-col>
        <a-col :span='2' class="align rightLine tone"></a-col>
        <a-col :span='2' class="align rightLine tone"></a-col>
        <a-col :span='3' class="align rightLine tone"></a-col>
        <a-col :span='2' class="align rightLine tone"></a-col>
        <a-col :span='2' class="align rightLine tone"></a-col>
        <a-col :span='3' class="align tone"></a-col>
      </a-row>
    </div>

    <a-row type="flex" justify="space-between">
      <a-col :span='6' class="align rightLine tone">
        <p style="margin: 10px 0 100px 0;">
          <a v-if="!moneyDisabled" @click="addInvioce" style="float: right;margin-right: 5px;">
            <a-icon type="plus" />新增应税项目
          </a>
        </p>
      </a-col>
      <a-col :span='2' class="align rightLine tone"></a-col>
      <a-col :span='2' class="align rightLine tone"></a-col>
      <a-col :span='2' class="align rightLine tone"></a-col>
      <a-col :span='2' class="align rightLine tone"></a-col>
      <a-col :span='3' class="align rightLine tone"></a-col>
      <a-col :span='2' class="align rightLine tone"></a-col>
      <a-col :span='2' class="align rightLine tone"></a-col>
      <a-col :span='3' class="align tone"></a-col>
    </a-row>
  </div>

</template>

<script>
import { mapState } from 'vuex'
import { conversionElement,conversionBranch,cloneObject,accSub,accAdd } from '@/utils/util'
import DetailList from '@/components/tools/DetailList'
const DetailListItem = DetailList.Item
import InvoicingDropDownItem from './invoicingDropDownItem'
import { getIndustryInfoChild } from '@/api/invoiceAdminister'
export default {
  name: 'invoicingDropDown',
  components:{
    DetailList,
    DetailListItem,
    InvoicingDropDownItem
  },
  props: ['taxContents','setVal'],
  data(){
    return{
      // taxContents: [  //开票内容
      //   {
      //     invoiceTypeCode: null,   //发票类目
      //     invoiceTypeName: null,
      //     ultraLimit: null,  //是否超出企业设置的经营范围  1 是  0否
      //     money: null,   //发票金额（不含税）
      //     taxMoney: null,   //发票金额（含税）
      //     unit: null,   //单位
      //     spec: null,   //规格型号
      //     num: null,   //数量
      //     unitPrice: null,   //单价
      //     nameGenre: null,  //其他类别
      //     name: null,
      //     value: null,
      //     isShow: true,
      //   }
      // ],  //开票内容
      // totalPrice: 0  //本次开票金额
      totalAstrict: 9900000,  //单张开票最大金额：9.9万
      newTreeData: [],  //开票列表

      moneyDisabled: false,
    }
  },
  computed:{
    ...mapState({
      vatIndex: state => state.invoice.vatIndex,  //专票增值税id
      vatRate: state => state.invoice.vatRate,  //专票增值税税率
      taxType: state => state.invoice.taxType,  //发票类型
    }),
    totalPrice:function(){
      const total = this.taxContents.reduce((prev,item) =>{
        return Number(item.money) + prev;
      },0)
      let newTotal = Number(total.toFixed(2));
      this.setVal && this.setVal(newTotal)
      // this.$emit('handleFather',this.taxContents,newTotal);
      return newTotal;
    },
    getTreeData(){
      return this.newTreeData;
    }
  },
  watch:{
    taxContents:{
      handler(vals) {
        this.resetList(vals);
      }
    },
    totalPrice(val){
      this.$store.dispatch('setResturantTotal', val);  //派发
      //本次开票数量
      let makeInvoiceNum;
      let obj = conversionBranch(val) / this.totalAstrict;
      if (Math.floor(obj) === obj){
        makeInvoiceNum = obj;
      }else{
        makeInvoiceNum = Math.floor(obj) + 1;
      }

      this.$store.dispatch('setInvoiceNum', makeInvoiceNum);
    },
  },
  created() {
    //从详情 变更申请 发起
    if (this.$route.query.varyType && this.$route.query.varyType == 1){
      this.moneyDisabled = true;
    }
  },
  mounted() {
    this.getMethodList();
  },
  methods:{
    resetList(list){
      //兼容历史数据处理invoiceTypeName
      for (let i=0;i<list.length;i++){
        if (list[i].name && list[i].value){

        }else{
          if (list[i].invoiceTypeName){
            let str = list[i].invoiceTypeName.split('*');
            list[i].name = str[0];
            list[i].value = str[1];
          }
        }
      }
      return list;
    },
    //  ---------------------------- 开票内容添加和删除 ↓ -----------------------
    //添加开票内容
    addInvioce(){
      if (this.taxContents.length >= 10){
        this.$message.warning('开票内容最多可添加至10个');
      }else {
        let data = {
          invoiceTypeCode: null,   //发票类目
          invoiceTypeName: null,
          ultraLimit: null,  //是否超出企业设置的经营范围  1 是  0否
          money: null,   //发票金额（不含税）
          taxMoney: null,   //发票金额（含税）
          unit: null,   //单位
          spec: null,   //规格型号
          num: null,   //数量
          unitPrice: null,   //单价
          nameGenre: null,  //其他类别
          name: null,
          value: null,
          isShow: true,
        };
        this.taxContents.push(data);
      }
    },
    //删除开票内容
    deleteRateFun(invoiceTypeCode,index){
      // this.getNonRepeating(this.newTreeData,invoiceTypeCode,false);
      this.taxContents.splice(index, 1);
      // this.changeEvent(invoiceTypeCode,0)
    },
    //校验开票内容
    verificationContent(){
      //校验税率是否选择
      if (!this.vatRate && this.taxType == 1 && !this.vatIndex){
        this.$message.warning('请先选择发票税率');
        return false;
      }else{
        //处理其他类型拼接invoiceTypeName值
        if (this.taxContents.length > 0){
          for (let k=0; k<this.taxContents.length; k++) {
            this.taxContents[k].num = Math.floor(parseInt(this.taxContents[k].num));
            this.taxContents[k].invoiceTypeName = this.taxContents[k].name + '*' + this.taxContents[k].value;
          }
        }

        //判断开票内容不能为空    every：若数组每一个对象都符合条件，则返回true ，只要有一个不符合条件就返回false。
        let bool = this.taxContents.every(item => {
          return item.name && item.value
        });
        //校验发票类目不能为空
        if (bool) {
          //校验发票类目不能重复
          // let repetition = this.categoriesRepetition();
          // if (repetition){
          //   this.$message.warning('发票类目不能重复，请重新选择');
          // }else{
            //校验开票金额不能为空
            let other = this.taxContents.every(item => {
              return item.money
            });
            if (other) {
              this.$emit('handleFather', this.taxContents, this.totalPrice);
              return true;
            } else {
              this.$message.warning('开票金额不能为空');
              return false;
            }
          // }
        } else {
          this.$message.warning('发票类目不能为空');
          return false;
        }
      }
    },
    //校验发票类目是否重复
    categoriesRepetition(){
      const hasDuplicates = this.hasDuplicateField(this.taxContents, 'invoiceTypeCode');
      if (hasDuplicates){
        const hasName = this.hasDuplicateField(this.taxContents, 'name');
        const hasValue = this.hasDuplicateField(this.taxContents, 'value');
        if (hasName && hasValue){
          return true;
        } else {
          return false;
        }
      }else {
        return false;
      }
    },
    hasDuplicateField(array, field) {
      const map = {};
      for (let i = 0; i < array.length; i++) {
        const value = array[i][field];
        if (map[value]) {
          return true;
        }
        map[value] = true;
      }
      return false;
    },
    //  ---------------------------- 初始数据开票内容 ↓ -----------------------
    //获取一级开票列表数据
    getMethodList(){
      let params = {};
      params.entId = this.$route.query.bizId;
      params.parentGroupCode = 2000000001;
      getIndustryInfoChild(params).then(res => {
        if (res.success) {
          let data = res.result || [];
          this.newTreeData = data;
        }else{
          this.$message.warning(res.message);
        }
      })
    },
  }
}
</script>

<style lang="less" scoped>
//公共
.tone{color: #9D6854;}
.mTop{margin-top: 10px;}
.padding{padding: 10px 0;}
.pTop{padding-top: 10px;}
.pLeft{padding-left: 20px;}
.topLine{border-top: 3px solid #9D6854;}
.rightLine{border-right: 3px solid #9D6854;}
.textLine{text-decoration: underline;cursor: pointer;}
.flex{display: flex;}
.align{text-align: center;}





.invoice_left{
  width: 100%;
  display: flex;
  flex-wrap: wrap;
}
.invoice_content {
  width: 100%;
  display: flex;
  //align-items: center;
}
</style>

